<template>
  <div>
    <div :class="isHiddenTitle ? 'hidden-class' : ''" class="title-container">
      <Title v-show="!isHiddenTitle" title="账号信息"/>
      <el-button size="small" class="quote-btn" @click="accountDialogShow">引用账号信息</el-button>
      <PlainCreateBtn :extra-class="{ 'mobile-create-btn': showMobilePage }" class="create-btn" style="font-weight: bold;" @click="addAccount">添加账号</PlainCreateBtn>
    </div>
    <el-tabs v-if="accountData.length" v-model="activeName" class="sign-tag-container" type="card">
      <el-tab-pane v-for="(item,index) in accountData" :key="index" :name="index.toString()" label="用户管理">
        <span slot="label">
          <div :title="item.accountsInfo.accountName || '请输入账号名称'" class="ft16 pane-label">{{ handleName(item.accountsInfo.accountName) }} <i class="icon el-icon-close" @click.stop="deleteItem(index)"/></div>
        </span>
        <AccountInfo
          :ref="`accountInfo-${item._uuid}`"
          v-model="item.accountsInfo"
          :row-span="rowSpan"
          :form-fly-user="formFlyUser"
          style="margin-bottom:8px;"
          @platformChange="platformChange($event, index)"/>
        <PriceInfo v-model="item.additionalKey" :platform-name="item.accountsInfo.platformName" :span="rowSpan" />
        <SignInfo
          :ref="`signInfo-${item._uuid}`"
          :row-span="rowSpan"
          :show-mobile-page="showMobilePage"
          v-model="item.contractInfo"
          :account-item="item"
          style="margin-bottom:8px;"
        />
        <CostInfo
          :ref="`priceInfo-${item._uuid}`"
          v-model="item.priceInfo"
          :row-span="rowSpan"
          :is-modify="isModify"
          :is-modify-price="item.priceInfo.isModifyPrice"
        />
        <ContractInfo
          :ref="`contractInf-${item._uuid}`"
          v-model="item.contractList"
          show-associate-btn
          @changeValue="syncContractForSignInfo(index, $event)"
          @onContractSelect="handleContractSelect($event, index)"
        />
      </el-tab-pane>
    </el-tabs>
    <div v-else class="empty-container">
      <img :src="emptyIcon" alt="">
      <div class="text">暂无账号信息，可通过点击右上角[<span class="blue">添加账号</span>]添加</div>
    </div>
    <AccountSelection
      ref="accountSelectionRef"
      :visible.sync="showAccountSelection"
      :multiple="true"
      :expand-params="accountExpandParams"
      @submit="handleAccountSelected"
    />
  </div>
</template>

<script>
/**
 *签约审批和销售供应商共用
 */
// components
import Title from '@/components/Title';
import SignInfo from './model/signInfo';
import AccountInfo from './model/account';
import CostInfo from './model/priceInfo';
import ContractInfo from './model/contractInfo';
import PriceInfo from '@/views/filter/components/createPriceInfo';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import AccountSelection from '@/components/resource/AccountSelection';
// img
import emptyIcon from '@/assets/home/emptyIcon.png';
// api
import { getPlatformConfig } from '@/api/signUp';
import { getResouceInfo } from '@/api/resource';
import { generateUUID } from '@/utils/tools';
import { getFirstDepartment } from '@/utils/index';
import { CONTRACT_TYPE } from '@/utils/const/contract';
import { referenceFieldsMapping } from '@/utils/signUpMappingResource';
import { getList as getContractList } from '@/api/legal';
import { mapState } from 'vuex';
export default {
  components: { Title, SignInfo, AccountInfo, CostInfo, DetailTabs, ContractInfo, AccountSelection, PriceInfo },
  model: {
    prop: 'accountData',
    event: 'changeValue'
  },
  props: {
    accountData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isModify: {
      type: Boolean,
      default: false
    },
    formFlyUser: {// 是否从飞来用户发起
      type: Boolean,
      default: false
    },
    rowSpan: {
      type: Number,
      default: 12
    },
    isHiddenTitle: {
      type: Boolean,
      default: false
    },
    pageFrom: { // 页面来源：supplierManage 飞博供应商
      type: String,
      default: ''
    },
    supplierInfo: {
      type: Object,
      default: null
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    openRealTimeVerify: { // 表单开启实时填写校验
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      emptyIcon,
      isFirstLoad: false,
      activeName: '0',
      showAccountSelection: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    accountExpandParams() { // 排除已签约、已续约、自动续约的账号
      return {
        signDetailStatus: '0,1,3,4,7'
      };
    },
    accountsInfo() { // 账号(基础)信息
      return {
        orderPlatformId: '', // 平台id
        accountName: '', // 账号名称
        link: '', // 主页链接
        accountCode: '', // 账号ID
        // operatingModelId: '',
        microtask: 0, // 是否挂靠
        fansNum: '', // 粉丝量
        tagName: [],
        preference: '', // 接单偏好
        dynamicKey: [],
        area: '', // 达人所在城市
        gender: null, // 性别
        // contentType: [], // 内容类别
        likeNum: null, // 点赞数
        commentNum: null, // 评论数
        favouritesNum: null, // 收藏数
        quotationPrice: null, // 报备价格(原对外报价)
        notReportPrice: null // 非报备价格
        // dynamicKey: this.jsonParse(this.dynamicKey) // 动态字段
      };
    },
    contractInfo() { // 签约信息
      return {
        agentId: this.userInfo.id,
        signDeptId: this.getFirstDepartment(this.userInfo.departmentAry),
        agentName: this.userInfo.userName,
        workWxCode: '',
        signDate: [],
        cooperation: '',
        cooperationDepartment: [],
        legalCode: null,
        settledScreenshot: [],
        autoRenewal: 1,
        signDept: [],
        schedule: null,
        reason: ''
      };
    },
    priceInfo() { // 价格信息
      return {
        profitSharingRemark: '',
        guaranteeRemark: '',
        profitSharingRatio: '',
        guaranteePrice: '',
        rebateRatio: '',
        dockingUsers: [],
        dynamicKey: []
        // dynamicKey: this.jsonParse(this.dynamicKey), // 动态字段
      };
    }
  },
  watch: {
    accountData: {
      handler(data) {
        if (data.length) {
          !this.isFirstLoad && (this.activeName = '0');
          data.forEach(item => {
            item.priceInfo.isModifyPrice = !!item.priceInfo.adjustPriceReason;
          });
          this.isFirstLoad = true;
        }
        this.$nextTick(() => this.openRealTimeVerify && this.realTimeValidate(data));
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getFirstDepartment,
    handleName(str = '') {
      if (!str) { return '请输入账号名称'; }
      if (str.length > 18) {
        return str.slice(0, 18) + '...';
      }
      return str;
    },
    // 实时填写校验
    realTimeValidate(list) {
      if (!list || !list.length) {
        this.$emit('showBadge', false);
        return;
      }
      let isPass = true;
      for (let i = 0; i < list.length; i++) {
        const accountValid = this.validateSection(list[i].accountsInfo, `accountInfo-${list[i]._uuid}`);
        const priceValid = accountValid && this.validateSection(list[i].priceInfo, `priceInfo-${list[i]._uuid}`);
        const signValid = priceValid && this.validateSignInfo(list[i].contractInfo, `signInfo-${list[i]._uuid}`);
        isPass = accountValid && priceValid && signValid;
        if (!isPass) break;
      }
      this.$emit('showBadge', !isPass);
    },
    // 验证账号信息&价格信息填写
    validateSection(data, refName) {
      let isPass = true;
      const currRef = this.$refs[refName];
      const allFields = currRef && currRef[0] && currRef[0].$refs['formRef'].fields.filter(field => field.isRequired) || [];
      let fixedFields; // 固定字段
      let dynamicFields = []; // 动态字段
      if (data.dynamicKey.length) {
        fixedFields = allFields.filter(field => data.dynamicKey.every(i => i.name !== field.prop));
        dynamicFields = allFields.filter(field => data.dynamicKey.some(i => i.name === field.prop));
      } else {
        fixedFields = allFields;
      }
      fixedFields.length && fixedFields.forEach(field => {
        if (!data[field.prop] && data[field.prop] !== 0) {
          isPass = false;
        }
      });
      dynamicFields.length && dynamicFields.forEach(field => {
        const targetField = data.dynamicKey.find(item => item.name === field.prop);
        if (!targetField.value && targetField.value !== 0) {
          isPass = false;
        }
      });
      return isPass;
    },
    // 验证签约信息填写
    validateSignInfo(data, refName) {
      let isPass = true;
      const currRef = this.$refs[refName];
      const allFields = currRef && currRef[0] && currRef[0].$refs['formRef'].fields || [];
      allFields.forEach(field => {
        if (field.isRequired && !data[field.prop] && data[field.prop] !== 0) {
          isPass = false;
        }
      });
      return isPass;
    },
    // 平台变化
    platformChange(platformId, index, cb = null) {
      getPlatformConfig(platformId).then((res) => {
        if (res.data && res.data.length) {
          this.setDynamic(res.data, index, cb);
        } else {
          this.setDynamic(null, index, cb);
        }
      });
      this.$forceUpdate(); // 解决平台切换价格信息监听不到的问题
    },
    accountDialogShow() {
      this.$refs['accountSelectionRef'].init([]);
      this.showAccountSelection = true;
    },
    /* handleAccountSelected(accountInfo) {
      if (accountInfo && accountInfo.mediumId) {
        getResouceInfo(accountInfo.mediumId).then(res => {
          this.addAccount(res.data);
        });
      }
      this.showAccountSelection = false;
    }, */
    handleAccountSelected(accountList) {
      const temp = this.accountData.slice(1);
      const mediumIds = [];
      temp.forEach(item => {
        if (item.accountsInfo.mediumId) {
          mediumIds.push(item.accountsInfo.mediumId);
        }
      });
      if (accountList && accountList.length) {
        // 创建请求数组
        const promiseArr = [];
        accountList.forEach(item => {
          if (!mediumIds.includes(item.mediumId)) {
            promiseArr.push(this.createPromise(item, false));
          }
        });
        // 串行执行请求
        this.executePromise(promiseArr);
      }
      this.showAccountSelection = false;
    },
    executePromise(arr) {
      arr.reduce((pre, next, index, carr) => {
        return pre.then(next);
      }, Promise.resolve());
    },
    createPromise(item) {
      const that = this;
      return (resolve, reject) =>
        new Promise((resolve, reject) => {
          getResouceInfo(item.mediumId).then(res => {
            const data = res.data;
            data.mediumId = item.mediumId;
            that.addAccount(data);
            resolve();
          }).catch(err => {
            console.log(err);
            reject();
          });
        });
    },
    handleContractSelect(data, index) {
      const currItem = this.accountData[index].contractInfo;
      currItem.legalCode = data && data.id ? data : null;
      if (data && data.contractType === CONTRACT_TYPE.KOL && data.autoRenewal != null) {
        currItem.autoRenewal = data.autoRenewal;
      }
      this.showRelatedContract = false;
      if (data && data.contractEffectStartDate && data.contractEffectEndDate) {
        currItem.signDate = [data.contractEffectStartDate, data.contractEffectEndDate];
      }
      this.$refs[`signInfo-${this.accountData[index]._uuid}`][0].unChangeSignDate = !!data;
      const insertList = data ? [data] : [];
      this.$set(this.accountData[index], 'contractList', insertList);
    },
    // 合同信息删除，关联合同字段同步移除
    syncContractForSignInfo(index) {
      this.accountData[index].contractInfo.legalCode = null;
      // 删除合同时，签约日期要可以修改
      if (this.$refs[`signInfo-${this.accountData[index]._uuid}`]) {
        this.$refs[`signInfo-${this.accountData[index]._uuid}`][0].unChangeSignDate = false;
      }
    },
    setDynamic(data, index, cb) {
      const item = this.accountData[index];
      const res = data ? data[0].item || [] : [];
      const accounts = res.find(i => i.name === '账号信息');
      const price = res.find(i => i.name === '价格信息');

      const accountsInfoDynamic = accounts ? accounts.item || [] : [];
      const priceInfoDynamic = price ? price.item || [] : [];
      if (item) {
        this.$set(item.accountsInfo, 'dynamicKey', accountsInfoDynamic);
        this.$set(item.priceInfo, 'dynamicKey', priceInfoDynamic);
        const accountsRequiredModel = this.getRequired(item.accountsInfo.dynamicKey);
        const priceInfoRequiredModel = this.getRequired(item.priceInfo.dynamicKey);
        this.$set(item.accountsInfo, 'requiredModel', accountsRequiredModel);
        this.$set(item.priceInfo, 'requiredModel', priceInfoRequiredModel);
        cb && cb();
      }
    },
    addAccount(accountInfo = null) {
      const data = {
        _uuid: generateUUID(),
        accountsInfo: _.cloneDeep(this.accountsInfo),
        contractInfo: _.cloneDeep(this.contractInfo),
        priceInfo: _.cloneDeep(this.priceInfo),
        additionalKey: {
          nextMonthReportPrice: {},
          nextMonthNotReportPrice: {},
          articlesPrice: {}
        },
        contractList: [] // 关联合同详细字段
      };
      // 获取资源详情数据并回填
      if (accountInfo) {
        Object.keys(referenceFieldsMapping).forEach(key => {
          let value = _.get(accountInfo, referenceFieldsMapping[key]);
          if (key === 'contractInfo.cooperationDepartment') { // 协作部门
            value = (value || []).map(i => i.id);
          } else if (key === 'contractInfo.signDate') { // 签约有效期
            const startDate = _.get(accountInfo, 'additionalKey.signStartDate');
            const endDate = _.get(accountInfo, 'additionalKey.signEndDate');
            if (startDate && endDate) {
              value = [startDate, endDate];
            }
          } else if (key === 'contractInfo.legalCode.id' && value) { // 关联合同信息，如果有值，搜索合同编号填充底部详细合同信息数据
            this.setContractDetail(value, data._uuid);
          }
          _.set(data, key, value);
        });
        if (accountInfo.additionalKey) {
          data.additionalKey = accountInfo.additionalKey;
          // 引用账号的additionalKey的相关数据可能为null，补上空对象防止报错
          if (!data.additionalKey.articlesPrice) {
            data.additionalKey.articlesPrice = {};
          }
          if (!data.additionalKey.nextMonthReportPrice) {
            data.additionalKey.nextMonthReportPrice = {};
          }
          if (!data.additionalKey.nextMonthNotReportPrice) {
            data.additionalKey.nextMonthNotReportPrice = {};
          }
        }
        this.$nextTick(() => {
          const currIndex = this.accountData.length - 1;
          this.activeName = currIndex + '';
          // 平台联动动态字段设置
          const platformId = _.get(accountInfo, referenceFieldsMapping['accountsInfo.orderPlatformId']);
          this.platformChange(platformId, currIndex, () => { this.syncDynamicField(data, accountInfo); });
        });
      } else {
        data.initNew = true;
      }
      if (!this.activeName || this.accountData.length === 0) {
        this.activeName = '0';
      }
      this.accountData.push(data);
      // 引用账号时，如果账号关联了合同，签约日期要禁止修改
      if (data.contractInfo.legalCode && data.contractInfo.legalCode.id) {
        this.$nextTick(() => {
          if (this.$refs[`signInfo-${data._uuid}`]) {
            this.$refs[`signInfo-${data._uuid}`][0].unChangeSignDate = true;
          }
        });
      }
    },
    syncDynamicField(signInfo = {}, accountInfo = {}) {
      const data = signInfo;
      // 同步自定义字段：小红书须同步健康状态和蒲公英信用等级字段
      if (accountInfo.platformTypeName === '小红书') {
        const syncFieldNames = [{ name: '健康状态', syncModule: 'accountsInfo', module: 'moreAccountInfo' }, { name: '蒲公英信用等级', syncModule: 'accountsInfo', module: 'moreAccountInfo' }];
        syncFieldNames.forEach(el => {
          const signUpField = data[el.syncModule].dynamicKey && data[el.syncModule].dynamicKey.find(i => i.name === el.name);
          const resourceField = accountInfo[el.module].dynamicKey && accountInfo[el.module].dynamicKey.find(i => i.name === el.name);
          if (signUpField && resourceField) {
            const idx = signInfo[el.syncModule].dynamicKey.findIndex(i => i.name === el.name);
            const newItem = signInfo[el.syncModule].dynamicKey[idx];
            const oldItem = resourceField;
            if (newItem.inputType === 1 && oldItem.inputType === 1) {
              let curOldItem = {};
              if (oldItem.options) {
                curOldItem = oldItem.options.find(j => j.value === oldItem.value);
              }
              const curNewItem = newItem.options.find(j => j.value === oldItem.value);
              if (curNewItem && curOldItem.label === curNewItem.label) {
                this.$set(newItem, 'value', oldItem.value);
              } else {
                this.$set(newItem, 'value', '');
              }
            } else if ((newItem.inputType === 1 && oldItem.inputType === 0) || (newItem.inputType === 0 && oldItem.inputType === 1)) {
              this.$set(newItem, 'value', '');
            } else {
              this.$set(newItem, 'value', oldItem.value);
            }
          }
        });
      }
    },
    setContractDetail(id, uuid) {
      const params = { ids: String(id), page: 1, perPage: 10 };
      getContractList(params).then(res => {
        if (res.code === 200) {
          const list = res.data && res.data.items || [];
          if (list.length) {
            const index = this.accountData.findIndex(i => i._uuid === uuid);
            index !== -1 && (this.accountData[index].contractList = [list.shift()]);
          }
        }
      });
    },
    jsonParse(arr) {
      if (!arr) return [];
      try {
        return JSON.parse(JSON.stringify(arr));
      } catch (error) {
        return [];
      }
    },
    initData() {
      if (this.accountData && this.accountData.length) {
        this.accountData.forEach(item => {
          if (item) {
            const accountsRequiredModel = this.getRequired(item.accountsInfo.dynamicKey);
            const priceInfoRequiredModel = this.getRequired(item.priceInfo.dynamicKey);
            this.$set(item.accountsInfo, 'requiredModel', accountsRequiredModel);
            this.$set(item.priceInfo, 'requiredModel', priceInfoRequiredModel);
          }
        });
      }
    },
    getRequired(dynamicKey) { // 获取必填字段
      const requiredModel = {};
      dynamicKey.forEach(i => {
        if (i.required) {
          const type = i.inputType === 0 ? '输入' : '选择';
          const validateType = (msg, item) => {
            return (rule, value, callback) => {
              if (item && (item.value || item.value === 0)) {
                callback();
              } else {
                callback(new Error(msg));
              }
            };
          };
          requiredModel[i.name] = [{ required: true, trigger: 'change', validator: validateType(`请${type}${i.name}`, i) }];
        }
      });
      return requiredModel;
    },
    deleteItem(index) {
      this.accountData.splice(index, 1);
      this.$nextTick(() => {
        if (index.toString() === this.activeName) {
          this.activeName = '0';
        } else if (Number(this.activeName) >= this.accountData.length) {
          this.activeName = (this.accountData.length - 1) + '';
        }
      });
    },
    validateForm() {
      const promise = [];
      this.accountData.forEach(i => {
        const signInfo = this.getValidateForm(`signInfo-${i._uuid}`);
        const accountInfo = this.getValidateForm(`accountInfo-${i._uuid}`);
        const priceInfo = this.getValidateForm(`priceInfo-${i._uuid}`);
        signInfo && promise.push(signInfo.validateForm());
        accountInfo && promise.push(accountInfo.validateForm());
        priceInfo && promise.push(priceInfo.validateForm());
      });
      return new Promise((resolve, reject) => {
        Promise.all(promise).then(res => {
          resolve(res);
        }).catch(() => {
          reject();
        });
      });
    },
    getValidateForm(refName) {
      if (!this.$refs[refName]) return null;
      if (Array.isArray(this.$refs[refName])) {
        return this.$refs[refName][0] || null;
      } else {
        return this.$refs[refName];
      }
    },
    clearValidate() {
      this.$nextTick(() => {
        const promise = [];
        this.accountData.forEach(i => {
          const accountInfo = this.getValidateForm(`accountInfo-${i._uuid}`);
          const priceInfo = this.getValidateForm(`priceInfo-${i._uuid}`);
          accountInfo && promise.push(accountInfo.$refs.formRef);
          priceInfo && promise.push(priceInfo.$refs.formRef);
        });
        promise.forEach(i => {
          i && i.clearValidate();
        });
      });
    },
    handleTabs(tabs) {
      tabs.forEach((i, index) => {
        i.id = index.toString();
      });
      return tabs;
    }
  }
};
</script>

<style lang="scss" scoped>
.title-container {
  display: flex;
  align-items: center;
  .quote-btn {
    margin-left: 8px;
    padding-left: 12px;
    padding-right: 12px;
    border-radius: 4px;
  }
}
.hidden-class {
  justify-content: flex-end;
}
.ft16 {
  font-size: 16px !important;
}
.pane-label {
  font-size: 14px;
  display: flex;
  align-items: center;
  height: 100%;
  .icon {
    font-size: 14px !important;
    color: #666666;
    margin-left: 8px;
    width: 14px !important;
    top: 0 !important;
    right: 0 !important;
    background-color:transparent !important;
  }
}
.btn-style {
  height: 32px;
  padding: 0;
  width: 80px;
  border: 1px solid #406ef4;
  color: #406ef4;
  background: #fff;
}
.white {
  background: #fff;
}
.no-border {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      // border-color: transparent;
      font-size: 14px;
    }
  }
}
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
  .text {
    font-size: 14px;
    font-weight: 400;
    text-align: left;
    color: #999999;
    line-height: 20px;
    margin-top: 10px;
  }
  .blue {
    color: #406ef4;
  }
  img {
    width: 120px;
  }
}
.sign-tag-container {
  &::v-deep {
    .el-tabs__header  {
      border-bottom: 1px solid #ddd;
      margin-top: 5px !important;
      margin-bottom: 16px !important;
      .el-tabs__nav {
        border: none !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px !important;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
